import { createToast, injectToastStyles } from '../common/toast.js';

document.addEventListener('DOMContentLoaded', function() {
    // 注入 Toast 样式
    injectToastStyles();
    
    // 加载保存的选项
    chrome.storage.local.get(['namespaceOptions', 'clusterOptions'], function(result) {
        // 加载集群选项
        const clusters = result.clusterOptions || [];
        const clusterList = document.getElementById('clusterList');
        clusterList.innerHTML = '';
        
        clusters.forEach(cluster => {
            const itemDiv = createOptionItem(cluster, 'cluster');
            clusterList.appendChild(itemDiv);
        });

        // 加载命名空间选项
        const namespaces = result.namespaceOptions || [];
        const optionList = document.getElementById('optionList');
        optionList.innerHTML = '';
        
        namespaces.forEach(namespace => {
            const itemDiv = createOptionItem(namespace, 'namespace');
            optionList.appendChild(itemDiv);
        });
    });

    // 加载设置
    loadSettings();
});

// 修改创建选项项目函数
function createOptionItem(value, type, isFixed = false) {
    const itemDiv = document.createElement('div');
    itemDiv.className = `option-item ${isFixed ? 'fixed-option-item' : ''}`;
    itemDiv.draggable = !isFixed;
    
    const dragHandle = document.createElement('span');
    dragHandle.className = 'drag-handle';
    dragHandle.innerHTML = '⋮⋮';
    
    const input = document.createElement('input');
    input.type = 'text';
    input.value = value;
    input.readOnly = isFixed;
    
    const deleteBtn = document.createElement('span');
    deleteBtn.className = 'delete-btn';
    deleteBtn.textContent = '×';
    deleteBtn.onclick = function() {
        if (!isFixed) {
            itemDiv.remove();
        }
    };
    
    if (!isFixed) {
        itemDiv.addEventListener('dragstart', handleDragStart);
        itemDiv.addEventListener('dragover', handleDragOver);
        itemDiv.addEventListener('drop', handleDrop);
        itemDiv.addEventListener('dragend', handleDragEnd);
    }
    
    itemDiv.appendChild(dragHandle);
    itemDiv.appendChild(input);
    itemDiv.appendChild(deleteBtn);
    return itemDiv;
}

// 拖拽相关变量
let draggedItem = null;

// 拖拽事件处理函数
function handleDragStart(e) {
    draggedItem = this;
    this.style.opacity = '0.4';
}

function handleDragOver(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
}

function handleDrop(e) {
    e.preventDefault();
    if (this !== draggedItem) {
        const allItems = [...document.querySelectorAll('.option-item')];
        const draggedIndex = allItems.indexOf(draggedItem);
        const droppedIndex = allItems.indexOf(this);
        
        if (draggedIndex < droppedIndex) {
            this.parentNode.insertBefore(draggedItem, this.nextSibling);
        } else {
            this.parentNode.insertBefore(draggedItem, this);
        }
    }
}

function handleDragEnd(e) {
    this.style.opacity = '1';
    draggedItem = null;
}

// 加载设置
function loadSettings() {
    chrome.storage.local.get(['kubectlOpenType'], function(result) {
        const openType = result.kubectlOpenType || 'tab'; // 默认为新标签页
        document.getElementById('kubectlOpenType').value = openType;
    });
}

// 保存所有选项
function saveOptions() {
    const saveBtn = document.getElementById('saveBtn');
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;

    // 获取现有的命名空间和集群选项
    const namespaceInputs = document.querySelectorAll('#optionList .option-item input');
    const clusterInputs = document.querySelectorAll('#clusterList .option-item input');
    
    const namespaceOptions = Array.from(namespaceInputs).map(input => input.value.trim()).filter(value => value !== '');
    const clusterOptions = Array.from(clusterInputs).map(input => input.value.trim()).filter(value => value !== '');
    
    // 获取 kubectl 打开方式
    const kubectlOpenType = document.getElementById('kubectlOpenType').value;

    // 保存所有配置
    chrome.storage.local.set({
        namespaceOptions,
        clusterOptions,
        kubectlOpenType
    }, function() {
        createToast('配置已保存', 'success');
        chrome.runtime.sendMessage({action: 'optionsUpdated'});
        
        setTimeout(() => {
            saveBtn.textContent = originalText;
            saveBtn.disabled = false;
        }, 500);
    });
}

// 添加键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl+S 或 Command+S (Mac)
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        saveOptions();
    }
});

// 添加新集群按钮事件
document.getElementById('addNewClusterBtn').onclick = function() {
    const clusterList = document.getElementById('clusterList');
    const itemDiv = createOptionItem('', 'cluster');
    clusterList.appendChild(itemDiv);
};

// 添加新选项
document.getElementById('addNewBtn').onclick = function() {
    const optionList = document.getElementById('optionList');
    const itemDiv = createOptionItem('');
    optionList.appendChild(itemDiv);
};

// 保存按钮事件
document.getElementById('saveBtn').onclick = saveOptions;